/**
 * Created by huachuan on 2016/1/14.
 */
angular.module('releasehomecontrollers',[])
  //发现的首页（约局）的Controller
  .controller('ReleaseHomeCtrl',function($scope,$rootScope,$state,$cordovaStatusbar,$timeout,Loading,$ionicActionSheet,$cordovaCamera,$cordovaImagePicker,$cordovaFileTransfer,Home,ENV,Toast,Storage,History,LBS){
    $scope.showImageUrlList = [];
    var memberId = '';
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get('member').member_id;
    });
    $scope.locationAddr = '所在位置';
    //获取当前位置
    $scope.getLocation = function(){
      if($scope.locationAddr!='所在位置'&&$scope.locationAddr!='定位中...'){
        $scope.locationAddr='所在位置';
      }else{
        LBS.getPosition();
        $scope.locationAddr = '定位中...';
      }
    }
    $scope.$on('LBS.locationSuccess',function(){
      var location = LBS.getLocation();
      var myPoint = new BMap.Point(location.longitude,location.latitude);
      var convertor = new BMap.Convertor();
      var pointArr = [];
      pointArr.push(myPoint);
      convertor.translate(pointArr, 1, 5, translateCallback);
    });
    translateCallback = function(data) {
      var translatePoint = data.points[0];
      var gc = new BMap.Geocoder();
      gc.getLocation(translatePoint, function (rs) {
        var addComp = rs.addressComponents;
        $scope.$apply(function () {
          $scope.locationAddr = addComp.city+addComp.district+addComp.street+addComp.streetNumber;
        });
      });
    }
     $scope.addHomePic = function(){
       $ionicActionSheet.show({
         buttons: [
           { text: '拍照' },
           {text: '从手机相册选取'}
         ],
         cancelText: '取消',
         buttonClicked: function (index) {
              if(index==0){
                getPictureFormCamera();
              }else if(index==1){
                getPictureFormAlbums();
              }
           return true;
         }
       });
     };
    //拍照获取图片
    getPictureFormCamera = function(){
      var options = {
        quality: 30,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.JPEG,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true,
        correctOrientation:true
      };
      if($scope.showImageUrlList.length<=9){
        $cordovaCamera.getPicture(options).then(function(image){
          Toast.showMessage("拍照成功");
          $scope.showImageUrlList.push(image);
        },function(error){
          Toast.showMessage("拍照取消");
        })
      }else{
        Toast.showMessage("上传的图片不能超过九张");
      }
    };
    $scope.removePicture = function(index){
        if(index>=0 && index<$scope.showImageUrlList.length){
          $scope.showImageUrlList.splice(index,1);
        }else{
          Toast.showMessage("取消选择的图片不存在");
        }
    }
    //从手机相册中获取图片
    getPictureFormAlbums = function() {
      var options = {
        maximumImagesCount: 9-$scope.showImageUrlList.length,
        quality: 30
      };
      $cordovaImagePicker.getPictures(options)
        .then(function (results) {
			// alert(results);
          $scope.showImageUrlList = $scope.showImageUrlList.concat(results);
          if(results.length==0){
            Toast.showMessage("选择图片取消");
          }else{
            Toast.showMessage("选择图片成功");
          }
        },function(error){
          Toast.showMessage("选择图片失败");
        })
    }
    $scope.home = {
      message:''
    };
    //发布酒窝
    var releaseMark = '';
    $scope.releaseHome = function(){
      var mhLocation = '';
      if($scope.locationAddr!='所在位置'&&$scope.locationAddr!='定位中...'){
        mhLocation = $scope.locationAddr;
      }
      if($scope.home.message=='' && $scope.showImageUrlList.length==0){
        Toast.showMessage("发布的酒窝不允许为空");
      }else{
        //如果发布的酒窝存在图片,则经过特殊处理
        if($scope.showImageUrlList.length>0){
          releaseMark = new Date().getTime()+"-memberId="+memberId+"-havePicture";
          //将要在界面上要显示的酒窝信息传回meeting-controllers
          var nowReleaseHome = {
            mh_content : $scope.home.message,
            member_id:memberId,
            picSrc:$scope.showImageUrlList,
            mark:releaseMark,
            mh_comment_num:0,
            mh_create_time:'上传中...',
            mh_location:mhLocation,
            isLocal:true
          };
          //把刚刚发布的酒窝保存存放在service里
          Home.setUploadingReleaseHome(true);//正在上传
          Home.saveNewReleaseHome(nowReleaseHome);
          Loading.showLoading();
          $timeout(function(){
            Loading.hideLoading();
            Toast.showMessage("发布酒窝成功");
            $state.transitionTo('tab.discoverIndex');
          },1000);
          //带图片上传的酒窝
          Home.releaseHomeHavePic(memberId,$scope.showImageUrlList,$scope.home.message,releaseMark,mhLocation);
        }else{
          //如果发布的酒窝没有图片,就秒发
          Loading.showLoading();
          Home.releaseHomeMessage(memberId,$scope.home.message,'','onlyContent',mhLocation);
        }
      }
    }
    //发送带图片的酒窝成功
    $scope.$on('Home.releaseHomePicUpdated',function(){
      Loading.hideLoading();
      Home.setUploadingReleaseHome(false);//发布成功
      Home.saveNewReleaseHome('');//清空保存的内容
    });
    //发布酒窝成功网络请求成功
    $scope.$on('Home.releaseHomeMessageUpdated',function(){
      Loading.hideLoading();
      var result = Home.getReleaseHomeJson();
      if(result.releaseHomeState){
        if(result.mark=='onlyContent'){
          Toast.showMessage('发布酒窝成功');
          Home.setNewRelease(true);
          $timeout(function(){
            $state.transitionTo('tab.discoverIndex');
          },1000);
        }
      }else{
        Toast.showMessage(result.releaseHomeMsg);
      }
    });
    //酒窝显示大图
    $scope.showBigImage= function(picIndex){
      var items = [];
      var pswpElement = document.querySelectorAll('.pswp')[0];
      for(i=0;i<$scope.showImageUrlList.length;i++){
        var imgWH =getNaturalWidth($scope.showImageUrlList[i]);
        var temp = {
          src:$scope.showImageUrlList[i],
          w:imgWH[0],
          h:imgWH[1]
        };
        items.push(temp);
      }
      var options = {
        index: picIndex,
        history: false,
        focus: false,
        loop: false,
       /* pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
     // $cordovaStatusbar.hide();
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
      //$cordovaStatusbar.show();
    }
    //点击返回按钮
    $scope.goback = function(){
      History.goback();
    }
  })

